package com.huike.pmps.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huike.pmps.dao.*;
import com.huike.pmps.model.constants.GlobalConstants;
import com.huike.pmps.model.dto.common.PageInfo;
import com.huike.pmps.model.entity.*;
import com.huike.pmps.model.vo.PageResult;
import com.huike.pmps.model.vo.Result;
import com.huike.pmps.model.vo.supplier.SupplierServiceContentVo;
import com.huike.pmps.model.vo.supplier.SupplierVo;
import com.huike.pmps.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hpsf.Decimal;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */
@Slf4j
@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    private ProvincesService provincesService;
    @Autowired
    private CitiesService citiesService;
    @Autowired
    private AreasService areasService;
    @Autowired
    private SupplierDao supplierDao;
    @Autowired
    private SupplierEvaluatesDao supplierEvaluatesDao;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private SupplierSettlementDetailDao supplierSettlementDetailDao;


    @Override
    public Result insertOne(Supplier supplier) {
      /*  Provinces provinces = provincesService.selectByProvinceName(supplier.getProvinceName());
        if (provinces != null) {
            supplier.setProvinceId(provinces.getProvinceId());
            supplier.setProvinceName(provinces.getProvince());
            Cities cities = citiesService.selectOne(provinces.getProvinceId().toString(), supplier.getCityName());
            if (cities != null) {
                supplier.setCityId(Integer.valueOf(cities.getCityId()));
                supplier.setCityName(cities.getCity());
                Areas areas = areasService.selectOne(cities.getCityId(), supplier.getAreaName());
                if (areas != null) {
                    supplier.setAreaId(Integer.valueOf(areas.getAreaId()));
                    supplier.setAreaName(areas.getArea());
                }
            }
        }*/

        if (supplier.getInitEvaluation() == null) {
            supplier.setInitEvaluation(0);
            supplier.setFinalEvaluation(0d);
        } else {
            supplier.setFinalEvaluation(Double.valueOf(supplier.getInitEvaluation()));
        }
        //导入标记(1非导入,2导入)
        supplier.setImportFlag(1);
        supplierDao.insert(supplier);
        return Result.success("操作成功", supplier.getId());
    }

    @Override
    public Result selectOneById(Integer id) {
        return Result.success(supplierDao.selectById(id));
    }

    @Override
    public Result selectByCondition(PageInfo pageInfo, String supplierName, Integer supplierTypeId, String provinceName, String serviceTypeName, String contractState) {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(supplierName))
            queryWrapper.like("supplier_name", supplierName);

        if (supplierTypeId != null)
            queryWrapper.eq("supplier_type_id", supplierTypeId);

        if (StringUtils.isNotBlank(provinceName))
            queryWrapper.like("province_name", provinceName);

        if (StringUtils.isNotBlank(serviceTypeName))
            queryWrapper.like("service_type_names", serviceTypeName);

        queryWrapper.orderByDesc("id");

        Page<Supplier> page = new Page<>(pageInfo.getPage(), pageInfo.getPageSize());
        Page<Supplier> pageList = supplierDao.selectPage(page, queryWrapper);
        if (pageList.getSize() > 0) {
            Calendar calendar = Calendar.getInstance();
            Date currentDate = new Date();
            long currentTime = currentDate.getTime();
            calendar.setTime(currentDate);

            List<Supplier> supplierList = new ArrayList<>();

            for (Supplier supplier : pageList.getRecords()) {

                if (supplier.getAgreementStartTime() == null && supplier.getAgreementEndTime() == null)
                    supplier.setContractState("未签订");
                if (supplier.getAgreementEndTime() != null) {
                    calendar.add(Calendar.DAY_OF_YEAR, 60);
                    long time = calendar.getTime().getTime();
                    //协议结束时间-当前时间 >60天
                    if ((supplier.getAgreementEndTime().getTime() - currentTime) / 1000 / 60 / 60 / 24 > 60)
                        supplier.setContractState("正常");
                    else if (currentTime - time < 0 && currentTime < supplier.getAgreementEndTime().getTime())
                        supplier.setContractState("即将到期");
                    else if (currentTime > supplier.getAgreementEndTime().getTime())
                        supplier.setContractState("已过期");
                }

                //供应商使用状态
                supplier.setSupplierState("使用中");
                if (supplier.getState() == 0) {
                    supplier.setSupplierState("已禁用");
                }
                Integer minuteOfCourses = supplierSettlementDetailDao.selectSupplierMinuteOfCourses(supplier.getId());
                if (minuteOfCourses != null && minuteOfCourses > supplier.getEstimateMonthCapacity())
                    supplier.setSupplierState("已饱和");
                //按合同状态筛选
                if (StringUtils.isNotBlank(contractState) && supplier.getContractState().contains(contractState))
                    supplierList.add(supplier);
            }

            if (supplierList.size() > 0)
                pageList.setRecords(supplierList);

            PageResult pageResult = PageResult.builder().pageNumber(pageList.getCurrent()).pageSize(pageList.getSize())
                    .total(pageList.getTotal()).rows(pageList.getRecords()).build();
            return Result.success(pageResult);
        } else {
            return Result.success("没有符合条件的记录");
        }
    }

    @Override
    public Result updateById(Supplier supplier) {

      /*  Provinces provinces = provincesService.selectByProvinceName(supplier.getProvinceName());
        if (provinces != null) {
            supplier.setProvinceId(provinces.getProvinceId());
            supplier.setProvinceName(provinces.getProvince());
            Cities cities = citiesService.selectOne(provinces.getProvinceId().toString(), supplier.getCityName());
            if (cities != null) {
                supplier.setCityId(Integer.valueOf(cities.getCityId()));
                supplier.setCityName(cities.getCity());
                Areas areas = areasService.selectOne(cities.getCityId(), supplier.getAreaName());
                if (areas != null) {
                    supplier.setAreaId(Integer.valueOf(areas.getAreaId()));
                    supplier.setAreaName(areas.getArea());
                }
            }

        }*/


        if (supplierDao.updateById(supplier) > 0) {
            return Result.success();
        } else {
            return Result.failure("没有可更新的内容");
        }
    }

    @Override
    public Result deleteById(Integer id) {
        if (supplierDao.deleteById(id) > 0) {
            return Result.success();
        } else {
            return Result.failure("没有可删除的内容");
        }
    }

    /**
     * 供应商类型(公司、个人)，查询供应商
     *
     * @param supplierTypeId
     * @return
     */
    @Override
    public Result selectBySupplierType(Integer supplierTypeId) {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        if (supplierTypeId != null) {
            queryWrapper.eq("supplier_type_id", supplierTypeId);
        }
        queryWrapper.eq("state", GlobalConstants.SUPPLIER_STATE_ON);
        List<Supplier> suppliers = supplierDao.selectList(queryWrapper);
        List<SupplierVo> supplierVoList = new ArrayList<>();
        for (Supplier supplier : suppliers) {
            supplierVoList.add(SupplierVo.builder().supplierId(Integer.valueOf(supplier.getId())).supplierName(supplier.getSupplierName()).finalEvaluation(supplier.getFinalEvaluation()).build());
        }
        return Result.success(supplierVoList);
    }

    @Override
    public Result selectSupplierServiceContent(Integer id) {
        Supplier supplier = supplierDao.selectById(id);
        String serviceTypeIds = supplier.getServiceTypeIds();
        String serviceTypeNames = supplier.getServiceTypeNames();
        if (StringUtils.isNotBlank(serviceTypeIds) && StringUtils.isNotBlank(serviceTypeNames)) {
            String[] fields1 = serviceTypeIds.split(",");
            String[] fields2 = serviceTypeNames.split("[/]");
            List<SupplierServiceContentVo> serviceContentVos = new ArrayList<>();
            for (int i = 0; i < fields1.length; i++) {
                SupplierServiceContentVo serviceContentVo = SupplierServiceContentVo.builder().supplierTypeId(Integer.valueOf(fields1[i])).supplierTypeName(fields2[i]).build();
                serviceContentVos.add(serviceContentVo);
            }
            return Result.success(serviceContentVos);
        } else {
            return Result.success();
        }
    }

    /**
     * 供应商导出
     */
    @Override
    public void exportSupplier(HttpServletResponse response, String supplierName, Integer supplierTypeId, String provinceName, String serviceTypeName, String contractState) {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(supplierName))
            queryWrapper.like("supplier_name", supplierName);

        if (supplierTypeId != null)
            queryWrapper.eq("supplier_type_id", supplierTypeId);

        if (StringUtils.isNotBlank(provinceName))
            queryWrapper.like("province_name", provinceName);

        if (StringUtils.isNotBlank(serviceTypeName))
            queryWrapper.like("service_type_names", serviceTypeName);

        List<Supplier> resultList = supplierDao.selectList(queryWrapper);

        List<Supplier> supplierList = new ArrayList<>();


        Calendar calendar = Calendar.getInstance();
        Date currentDate = new Date();
        long currentTime = currentDate.getTime();
        calendar.setTime(currentDate);
        for (Supplier supplier : resultList) {
            if (supplier.getAgreementStartTime() == null && supplier.getAgreementEndTime() == null)
                supplier.setContractState("未签订");
            if (supplier.getAgreementEndTime() != null) {
                calendar.add(Calendar.DAY_OF_YEAR, 60);
                long time = calendar.getTime().getTime();
                //协议结束时间-当前时间 >60天
                if ((supplier.getAgreementEndTime().getTime() - currentTime) / 1000 / 60 / 60 / 24 > 60)
                    supplier.setContractState("正常");
                else if (currentTime - time < 0 && currentTime < supplier.getAgreementEndTime().getTime())
                    supplier.setContractState("即将到期");
                else if (currentTime > supplier.getAgreementEndTime().getTime())
                    supplier.setContractState("已过期");
            }

            //按合同状态筛选
            if (StringUtils.isNotBlank(contractState) && supplier.getContractState().contains(contractState))
                supplierList.add(supplier);
        }
        if (supplierList.size() == 0)
            supplierList = resultList;


        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("export_excel/supplier_template.xlsx");
        XSSFWorkbook xssfWorkbook = null;
        try {
            xssfWorkbook = new XSSFWorkbook(in);
            //获取第一个工作表sheet
            XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
            for (int i = 0; i < supplierList.size(); i++) {
                Supplier supplier = supplierList.get(i);
                XSSFRow row = sheetAt.createRow(i + 1);

                //供应商名称
                XSSFCell supplierNameCell = row.createCell(0);
                supplierNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplier.getSupplierName()))
                    supplierNameCell.setCellValue(supplier.getSupplierName());


                //供应商类型
                XSSFCell supplierTypeNameCell = row.createCell(1);
                supplierTypeNameCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplier.getSupplierTypeName()))
                    supplierTypeNameCell.setCellValue(supplier.getSupplierTypeName());
                //省份
                if (supplier.getProvinceId() != null) {
                    XSSFCell provinceCell = row.createCell(2);
                    provinceCell.setCellType(CellType.STRING);
                    provinceCell.setCellValue(provincesService.selectByProvinceId(supplier.getProvinceId()).getProvince());
                }
                //市
                if (supplier.getCityId() != null) {
                    XSSFCell cityCell = row.createCell(3);
                    cityCell.setCellType(CellType.STRING);
                    cityCell.setCellValue(citiesService.selectByCityId(supplier.getCityId().toString()).getCity());
                }
                //区
                if (supplier.getAreaId() != null) {
                    XSSFCell areaCell = row.createCell(4);
                    areaCell.setCellType(CellType.STRING);
                    areaCell.setCellValue(areasService.selectByAreaId(supplier.getAreaId().toString()).getArea());
                }

                //详细地址
                XSSFCell addressCell = row.createCell(5);
                addressCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplier.getAddress()))
                    addressCell.setCellValue(supplier.getAddress());

                //联系人
                XSSFCell contactsCell = row.createCell(6);
                contactsCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplier.getContacts()))
                    contactsCell.setCellValue(supplier.getContacts());

                //联系电话
                XSSFCell phoneCell = row.createCell(7);
                phoneCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplier.getPhone()))
                    phoneCell.setCellValue(supplier.getPhone());

                //企业邮箱
                XSSFCell emailCell = row.createCell(8);
                emailCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplier.getEmail()))
                    emailCell.setCellValue(supplier.getEmail());

                //协议编号
                XSSFCell agreementNoCell = row.createCell(9);
                agreementNoCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplier.getAgreementNo()))
                    agreementNoCell.setCellValue(supplier.getAgreementNo());

                //协议开始日期
                XSSFCell agreementStartTimeCell = row.createCell(10);
                agreementStartTimeCell.setCellType(CellType.STRING);
                if (supplier.getAgreementStartTime() != null)
                    agreementStartTimeCell.setCellValue(simpleDateFormat.format(supplier.getAgreementStartTime()));

                //协议结束日期
                XSSFCell agreementEndTimeCell = row.createCell(11);
                agreementEndTimeCell.setCellType(CellType.STRING);
                if (supplier.getAgreementEndTime() != null)
                    agreementEndTimeCell.setCellValue(simpleDateFormat.format(supplier.getAgreementEndTime()));

                //预计月承接量
                XSSFCell estimateMonthCapacityCell = row.createCell(12);
                estimateMonthCapacityCell.setCellType(CellType.STRING);
                if (supplier.getEstimateMonthCapacity() != null)
                    estimateMonthCapacityCell.setCellValue(supplier.getEstimateMonthCapacity());

                //可提供的服务
                XSSFCell serviceTypeNamesCell = row.createCell(13);
                serviceTypeNamesCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplier.getServiceTypeNames()))
                    serviceTypeNamesCell.setCellValue(supplier.getServiceTypeNames());

                //报价
                XSSFCell quotationCell = row.createCell(14);
                quotationCell.setCellType(CellType.STRING);
                if (supplier.getQuotation() != null)
                    quotationCell.setCellValue(supplier.getQuotation());

                //综合评分
                XSSFCell finalEvaluationCell = row.createCell(15);
                finalEvaluationCell.setCellType(CellType.STRING);
                if (supplier.getFinalEvaluation() != null)
                    finalEvaluationCell.setCellValue(supplier.getFinalEvaluation());

                //公司介绍
                XSSFCell companyProfileCell = row.createCell(16);
                companyProfileCell.setCellType(CellType.STRING);
                if (StringUtils.isNotBlank(supplier.getCompanyProfile()))
                    companyProfileCell.setCellValue(supplier.getCompanyProfile());
            }
            String fileName = "supplier_" + new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()) + ".xlsx";
            response.setContentType("application/octet-stream"); // 响应内容格式
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            xssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            xssfWorkbook.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 供应商导入
     *
     * @param file
     * @return
     */
    @Override
    public Result insertImportSupplier(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.failure("文件为空");
        }
        try {
            //根据路径获取这个操作excel的实例
            XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
            //根据页面index 获取sheet页
            XSSFSheet sheet = wb.getSheetAt(0);
            //获取标题行
            XSSFRow titleRow = sheet.getRow(0);
            String[] titleRowArray = new String[]{"供应商名称", "供应商类型", "省份", "市", "区/县", "详细地址", "联系人", "联系电话", "企业邮箱", "协议编号", "协议开始日期", "协议结束日期", "可提供的服务", "月承接量", "相关报价", "综合评分", "公司介绍", "是否禁用"};
            for (int i = 0; i < titleRowArray.length; i++) {
                if (!titleRowArray[i].equals(titleRow.getCell(i).getStringCellValue()))
                    return Result.failure("供应商模板标题行已被修改，请勿修改供应商模板标题行");
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            List<Supplier> supplierList = new ArrayList<>();
            XSSFRow row = null;
            //循环sheet页中数据从第二行开始，第一行是标题
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                //获取每一行数据
                row = sheet.getRow(i);

                //供应商名称
                if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 供应商名称为空");
                String supplierName = row.getCell(0).toString();

                //供应商类型名称
                if (row.getCell(1) == null || StringUtils.isBlank(row.getCell(1).toString()))
                    return Result.failure("本次导入全部失败，第【" + i + "】条数据 供应商类型为空");
                String supplierTypeName = row.getCell(1).toString();

                //供应商类型ID
                Integer supplierTypeId = null;
                if (StringUtils.isNotBlank(supplierTypeName)) {
                    Dictionary dictionary = dictionaryService.selectByOne(supplierTypeName, GlobalConstants.DICTIONARY_SUPPLIER_TYPE);
                    if (dictionary == null)
                        return Result.failure("本次导入全部失败，第【" + i + "】条数据 供应商是类型只能是 公司 或 个人");
                    supplierTypeId = dictionary.getId();
                    supplierTypeName = dictionary.getName();
                }

                //省份
                String provinceName = null;
                Integer provinceId = null;
                if (row.getCell(2) != null && StringUtils.isNotBlank(row.getCell(2).toString())) {
                    provinceName = row.getCell(2).getStringCellValue();
                    if (StringUtils.isNotBlank(provinceName)) {
                        Provinces provinces = provincesService.selectByProvinceName(provinceName);
                        if (provinces == null)
                            return Result.failure("本次导入全部失败，第【" + i + "】条数据,  " + supplierName + "  的省份信息填写错误,请检查后再次上传");
                        provinceId = provinces.getProvinceId();
                    }
                }

                //市
                String cityName = null;
                Integer cityId = null;
                if (row.getCell(3) != null && StringUtils.isNotBlank(row.getCell(3).toString())) {
                    cityName = row.getCell(3).toString();
                    if (StringUtils.isNotBlank(provinceName)) {
                        Cities cities = citiesService.selectOne(provinceId.toString(), cityName);
                        if (cities == null)
                            return Result.failure("本次导入全部失败，第【" + i + "】条数据,  " + supplierName + "  的城市信息填写错误,请检查后再次上传");
                        cityId = Integer.valueOf(cities.getCityId());
                    }
                }

                //区/县
                Integer areaId = null;
                String areaName = null;
                if (row.getCell(4) != null && StringUtils.isNotBlank(row.getCell(4).toString())) {
                    areaName = row.getCell(4).getStringCellValue();
                    if (StringUtils.isNotBlank(areaName)) {
                        Areas areas = areasService.selectOne(cityId.toString(), areaName);
                        if (areas == null)
                            return Result.failure(supplierName + " 区/县信息填写错误,请检查后再次上传");
                        areaId = Integer.valueOf(areas.getAreaId());
                    }
                }

                //详细地址
                String address = row.getCell(5) == null || StringUtils.isBlank(row.getCell(5).toString()) ? null : row.getCell(5).toString();
                //联系人
                String contacts = row.getCell(6) == null || StringUtils.isBlank(row.getCell(6).toString()) ? null : row.getCell(6).toString();
                //联系电话
                String phone = row.getCell(7) == null || StringUtils.isBlank(row.getCell(7).toString()) ? null : row.getCell(7).toString();
                //企业邮箱
                String email = row.getCell(8) == null || StringUtils.isBlank(row.getCell(8).toString()) ? null : row.getCell(8).toString();
                //协议编号
                String agreementNo = row.getCell(9) == null || StringUtils.isBlank(row.getCell(9).toString()) ? null : row.getCell(9).toString();
                //协议开始日期
                Date agreementStartTime = row.getCell(10) == null || StringUtils.isBlank(row.getCell(10).toString()) ? null : row.getCell(10).getDateCellValue();
                //协议结束日期
                Date agreementEndTime = row.getCell(11) == null || StringUtils.isBlank(row.getCell(11).toString()) ? null : row.getCell(11).getDateCellValue();
                //可提供的服务
                String serviceTypes = row.getCell(12) == null || StringUtils.isBlank(row.getCell(12).toString()) ? null : row.getCell(12).toString();
                //服务类型ID集合
                String serviceTypeIds = "";
                //服务类型名称集合
                String serviceTypeNames = "";

                if (StringUtils.isNotBlank(serviceTypes)) {
                   /* if (serviceTypes.contains("整包")) {
                        List<Dictionary> dictionaries = dictionaryService.selectListByType(GlobalConstants.DICTIONARY_SUPPLIER_SERVICE_CONTENT_TYPE);
                        for (Dictionary dictionary : dictionaries) {
                            if (!dictionary.getName().contains("整包")) {
                                serviceTypeIds += dictionary.getId() + ",";
                                serviceTypeNames += dictionary.getName() + "/";
                            }
                        }
                        if (StringUtils.isNotBlank(serviceTypeIds))
                            serviceTypeIds = serviceTypeIds.substring(0, serviceTypeIds.length() - 1);
                        if (StringUtils.isNotBlank(serviceTypeNames))
                            serviceTypeNames = serviceTypeNames.substring(0, serviceTypeNames.length() - 1);
                    } else {*/
                    String[] fields = serviceTypes.split("[/]");
                    if (fields.length > 0) {
                        for (String st : fields) {
                            Dictionary dictionary = dictionaryService.selectByOne(st, GlobalConstants.DICTIONARY_SUPPLIER_SERVICE_CONTENT_TYPE);
                            if (dictionary != null) {
                                serviceTypeIds += dictionary.getId() + ",";
                                serviceTypeNames += dictionary.getName() + "/";
                            }
                        }
                        if (StringUtils.isNotBlank(serviceTypeIds))
                            serviceTypeIds = serviceTypeIds.substring(0, serviceTypeIds.length() - 1);
                        if (StringUtils.isNotBlank(serviceTypeNames))
                            serviceTypeNames = serviceTypeNames.substring(0, serviceTypeNames.length() - 1);
                    }
                    //}
                }
                //预计月承接量
                Integer estimateMonthCapacity = row.getCell(13) == null || StringUtils.isBlank(row.getCell(13).toString()) ? null : Double.valueOf(row.getCell(13).toString()).intValue();
                //报价
                String quotation = row.getCell(14) == null || StringUtils.isBlank(row.getCell(14).toString()) ? null : row.getCell(14).toString();
                //综合评分
                Double finalEvaluation = row.getCell(15) == null || StringUtils.isBlank(row.getCell(15).toString()) ? 0d : Double.valueOf(row.getCell(15).toString());
                //公司介绍
                String companyProfile = row.getCell(16) == null || StringUtils.isBlank(row.getCell(16).toString()) ? null : row.getCell(16).toString();
                //是否禁用
                Integer state = row.getCell(17) == null || StringUtils.isBlank(row.getCell(17).toString()) ? 1 : row.getCell(17).toString() == "是" ? 0 : 1;

                //共建供应商实体
                Supplier supplier = Supplier.builder().supplierName(supplierName).supplierTypeId(supplierTypeId).supplierTypeName(supplierTypeName)
                        .provinceId(provinceId).cityId(cityId).areaId(areaId).address(address).contacts(contacts).phone(phone).email(email).agreementNo(agreementNo)
                        .agreementStartTime(agreementStartTime).agreementEndTime(agreementEndTime).serviceTypeIds(serviceTypeIds).serviceTypeNames(serviceTypeNames)
                        .estimateMonthCapacity(estimateMonthCapacity).quotation(quotation).initEvaluation(finalEvaluation.intValue())
                        .finalEvaluation(finalEvaluation).companyProfile(companyProfile).importFlag(2).state(state).build();
                supplierList.add(supplier);
            }
            supplierDao.insertSupplierBatch(supplierList);
            return Result.success();
        } catch (IOException e) {
            log.error(e.getMessage());
            return Result.failure("PO导入失败，请检查数据格式是否符合模板要求：" + e.getMessage());
        }
    }

    @Override
    public Supplier selectOneBySupplierName(String supplierName) {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("supplier_name", supplierName);
        return supplierDao.selectOne(queryWrapper);
    }



}
